package net.kazed.nextaction.context.activity;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

import net.kazed.nextaction.R;
import net.kazed.nextaction.database.GtdContext;

public class ContextEditorActivity extends Activity {

    private static final String cTag = "ContextEditorActivity";
   
    private static final int MENU_REVERT = Menu.FIRST;
    private static final int MENU_DELETE = Menu.FIRST + 1;
    
    private Cursor cursor;
    private boolean isNew;
    private Uri itemUri;
    private GtdContext originalContext;
    private EditText nameWidget;
        
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        // Do some setup based on the action being performed.
        final Intent intent = getIntent();
        final String action = intent.getAction();
        if (action.equals(Intent.ACTION_EDIT)) {
            // Requested to edit: set that state, and the data being edited.
            isNew = false;
            itemUri = intent.getData();
            Intent returnIntent = new Intent();
            returnIntent.setData(itemUri);
            setResult(RESULT_OK, returnIntent);
        } else if (action.equals(Intent.ACTION_INSERT)) {
            // Requested to insert: set that state, and create a new entry
            // in the container.
           isNew = true;
           originalContext = new GtdContext("New context");
           ContentValues values = new ContentValues();
           Uri parentUri = intent.getData();
           String parentPath = parentUri.getLastPathSegment();
           try {
              Integer parentId = null;
              parentId = Integer.parseInt(parentPath);
              originalContext.setParentContextId(parentId);
           } catch (NumberFormatException e) {
           }
           originalContext.toValues(values);
           itemUri = getContentResolver().insert(GtdContext.CONTENT_URI, values);
           cursor = managedQuery(itemUri, GtdContext.FULL_PROJECTION.getFieldNames(), null, null, null);

            // If we were unable to create a new item, then just finish
            // this activity.  A RESULT_CANCELED will be sent back to the
            // original activity if they requested a result.
            if (itemUri == null) {
                Log.e(cTag, "Failed to insert new item into "
                        + getIntent().getData());
                finish();
                return;
            }
            // The new entry was created, so assume all will end well and
            // set the result to be returned.
            // KZ - put this in onSaveInstanceState or onPause ?
          Bundle bundle = new Bundle();
          bundle.putString(ContextsActivity.SELECTED_ITEM, itemUri.toString());
          Intent returnIntent = new Intent();
          returnIntent.setData(itemUri);
          returnIntent.putExtras(bundle);
          setResult(RESULT_OK, returnIntent);
        } else {
            finish();
            return;
        }

        cursor = managedQuery(itemUri, GtdContext.FULL_PROJECTION.getFieldNames(), null, null, null);
        
        setupView();
    }
    
   private void setupView() {
      setContentView(R.layout.context_editor);
      nameWidget = (EditText) findViewById(R.id.name);
   }

   @Override
    protected void onResume() {
        Log.d(cTag, "onResume+");
        super.onResume();

        // If we didn't have any trouble retrieving the data, it is now
        // time to get at the stuff.
        if (cursor != null) {
            // Make sure we are at the one and only row in the cursor.
            cursor.moveToFirst();

            // Modify our overall title depending on the mode we are running in.
            if (isNew) {
               setTitle(R.string.title_new_context);
            } else {
                setTitle(R.string.title_edit_context);
            }
            
            originalContext = new GtdContext(cursor);
            populateFields(originalContext);

        } else {
            setTitle(getText(R.string.error_title));
            nameWidget.setText(getText(R.string.error_message));
        }
        
        // select the description
        nameWidget.selectAll();
    }

   private void populateFields(GtdContext context) {
      nameWidget.setTextKeepState(context.getName());
   }
    
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
    	Log.d(cTag, "Got resultCode " + resultCode + " with data " + data);		
	}
    
    @Override
    protected void onPause() {
        Log.d(cTag, "onPause+");
        super.onPause();

        // The user is going somewhere else, so make sure their current
        // changes are safely saved away in the provider.  We don't need
        // to do this if only viewing.
        if (cursor != null) {
            String name = nameWidget.getText().toString();
            int length = name.length();

            // If this activity is finished, and there is no text, then we
            // do something a little special: simply delete the context entry.
            // Note that we do this both for editing and inserting...  it
            // would be reasonable to only do it when inserting.
            if (isFinishing() && (length == 0)) {
                setResult(RESULT_CANCELED);
                // TODO validation - produce error message
                deleteItem();

            // Get out updates into the provider.
            } else {
               GtdContext context = new GtdContext(cursor);
               context.setName(name);
            	writeItem(cursor, context);

                // Commit all of our changes to persistent storage.  Note the
                // use of managedCommitUpdates() instead of
                // mCursor.commitUpdates() -- this lets Activity take care of
                // requerying the new data if needed.
            	// managedCommitUpdates(mCursor);
            }
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       Resources resources = getResources();
       menu.add(0, MENU_REVERT, 0, resources.getString(R.string.menu_revert))
          .setIcon(android.R.drawable.ic_menu_revert).setAlphabeticShortcut('r');
       menu.add(0, MENU_DELETE, 1, resources.getString(R.string.menu_delete))
          .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d');
       return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case MENU_REVERT:
          populateFields(originalContext);
          break;
       case MENU_DELETE:
          getContentResolver().delete(itemUri, null, null);
          finish();
          break;
       }
       return super.onOptionsItemSelected(item);
    }
    
    protected void writeItem(Cursor cursor, GtdContext context) {
      ContentValues values = new ContentValues();
      context.toValues(values);
      getContentResolver().update(itemUri, values, null, null);
    }

    /**
     * Take care of deleting a context.  Simply deletes the entry.
     */
    protected void deleteItem() {
        nameWidget.setText("");
    }
    
}
